package com.gongguizhijia.Util;

import org.apache.commons.lang3.StringUtils;

import static java.util.Arrays.copyOf;

/**
 * @author Chenglei
 * @date 2021/6/10 17:45
 * <p>
 * 常用方法 工具
 */
public class Utils {

    /**
     * 命令中需要每两个字节空一格
     *
     * @param replace
     * @return
     */
    public static String getFileAddSpace(String replace) {
        if (StringUtils.isNotBlank(replace)) {
            String regex = "(.{2})";
            replace = replace.replaceAll(regex, "$1 ");
        }
        return replace;
    }

    /**
     * 判断命令是否需要补足  补0   例如  21 5   =====》   21 05
     *
     * @param order
     * @return
     */
    public static String getOrderAddZero(String order) {
        String newOrder = null;
        if (order.length() % 2 != 0) {
            newOrder = order.substring(0, order.length() - 1) + "0" + order.substring(order.length() - 1, order.length()).toUpperCase();
        } else {
            newOrder = order.toUpperCase();
        }
        return newOrder;
    }

    /**
     * 转换成 16 进制
     *
     * @param n
     * @return
     */
    public static String intToHex(int n) {
        StringBuffer s = new StringBuffer();
        String a;
        char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
            s.append(b[n % 16]);
            n = n / 16;
        }
        a = s.reverse().toString();
        return a;
    }

    /**
     * 获取16进制文件集
     *
     * @return
     */
    public static String[] getArrForHex() {

        String[] arr = new String[]{"X01", "X02", "X03", "X04", "X05", "X06", "X07", "X08", "X09",
                "X0A", "X0B", "X0C", "X0D", "X0E", "X0F", "X10"};
        arr = copyOf(arr, 1984);

        for (int i = 16; i <= 1984; i++) {
            arr[i - 1] = "X" + Utils.intToHex(i);
        }
        return arr;
    }


    /**
     * 去除 多于的 0
     *
     * @param result
     * @return
     */
    public static String subNumberText(String result) {
        if (result == null) {
            return "";
        }
        //代表是小数
        if (result.contains(".")) {
            while (true) {
                if (result.charAt(result.length() - 1) == '0') {
                    result = result.substring(0, result.length() - 1);
                } else {
                    if (result.endsWith(".")) {
                        result = result.substring(0, result.length() - 1);
                    }
                    break;
                }
            }
        }
        return result;
    }

//    public static void main(String[] args) {
//        String s = subNumberText("1.0");
//        System.out.println("s = " + s);
//    }

}
